package info.cs52.fes;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class Application implements ServletContextListener {

	private static EntityManagerFactory emf;
	private static String path;

	@Override
	public void contextInitialized(ServletContextEvent evt) {
		emf = Persistence.createEntityManagerFactory("fes");
		path = evt.getServletContext().getInitParameter("path");
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent evt) {
		if (emf != null) {
			emf.close();
		}
	}

	public static EntityManagerFactory getEntityManagerFactory() {
		return emf;
	}
	
	private static ThreadLocal<EntityManager> managerLocal = new ThreadLocal<EntityManager>();
	
	public static EntityManager getEntityManager() {
		if (managerLocal.get() == null || !managerLocal.get().isOpen()) {
			managerLocal.set(emf.createEntityManager());
		}
		return managerLocal.get();
	}

	public static String getPath() {
		return path;
	}
	
}
